package com.raft.core.rpc.nio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.eventbus.EventBus;
import com.raft.core.node.NodeId;

import io.netty.channel.ChannelHandlerContext;

/**用于连接远程节点的处理器，除了基本的转发远程节点回复的消息外，还需要在连接之后马上发送自己的nodeId。在netty中，连接后立刻发送nodeId消息可以通过重载channelActive方法来实现
 * @author zhangsulei
 *
 */
class ToRemoteHandler extends AbstractHandler {

    private static final Logger logger = LoggerFactory.getLogger(ToRemoteHandler.class);
    private final NodeId selfNodeId;

    ToRemoteHandler(EventBus eventBus, NodeId remoteId, NodeId selfNodeId) {
        super(eventBus);
        this.remoteId = remoteId;
        this.selfNodeId = selfNodeId;
    }

    // 连接成功后，发送自己的节点id
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        ctx.write(selfNodeId);
        channel = new NioChannel(ctx.channel());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.debug("receive {} from {}", msg, remoteId);
        super.channelRead(ctx, msg);
    }

}
